<?php
error_reporting(E_ERROR );
class XiamiBridge{
	//加载缓存
	private function loadcache($hash){
		$cachefile = $this->cachedir().$hash;
	 if (file_exists($cachefile)) {
	 	return unserialize(file_get_contents($cachefile));
	 } else {
	 	return false;
	 }
	}
	//存储缓存
	private function savecache($data,$hash){
		$files = array_diff(scandir($this->cachedir()), Array( ".", ".." ) );
		if($files){
			$limit = 20;
			while($limit>1 && count($files)>$limit-1){
				unlink($this->cachedir().array_pop($files));
			}
		}
		$cachefile = $this->cachedir().$hash;
		$this->writecachefile($data,$cachefile);
	}
	private function cachedir() {
		$_dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . "cache" . DIRECTORY_SEPARATOR;
		if(!file_exists($_dir)){
			mkdir($_dir);
		}
		return $_dir;
	}
	private function writecachefile($_array, $_file, $_append = false) {
		$_ser = serialize($_array);
		# write to cache
		if ($_append) {
			$_f = @fopen($_file, 'w');
		} else {
			$_f = @fopen($_file, 'w+');
		}
		if ($_f) {
			fwrite($_f, $_ser, strlen($_ser));
			fclose($_f);
		}
	}
	public function getContent($t,$k){
		$k = trim($k);
		if($k){
			if($content = $this->loadcache(base64_encode($t.$k))){
				return $content;
			}else{
				$url = 'http://www.xiami.com/search/json?t='.$t.'&n=1&k='.urlencode($k);
				$content = file_get_contents($url);
				$this->savecache($content,base64_encode($t.$k));
				return $content;
			}
		}
	}
}
//
if(function_exists('file_get_contents')){
	header('application/json');
	$k = $_GET['k'];
	$type = $_GET['t'];
	if(!in_array($type,array('song','album','artist'))){
		$type = 'song';
	}
	$t_arr = array('song'=>1,'album'=>2,'artist'=>3,'music'=>4);
	$t = $t_arr[$type];
	$bridge = new XiamiBridge();
	echo $bridge->getContent($t,$k);
}
?>